package dk.sdu.flexibus.communications;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;
import android.util.Log;

public abstract class AbstractCommunicationsProvider {
	protected static String NAMESPACE = "http://www.madis.dk/Uni/FlexiBus";
	protected static String URL = "http://www.flexibus.madis.dk/WebService.asmx";

	public void sendRequest() {
		SoapObject request = new SoapObject(NAMESPACE, getMethodName());
		composeMessage(request);
		SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		soapEnvelope.dotNet = true;
		soapEnvelope.setOutputSoapObject(request);

		CallServiceTask task = getCallServiceTask();
		task.execute(soapEnvelope);

	}
	protected abstract void composeMessage(SoapObject request);
	protected abstract String getMethodName();
	protected abstract String getSoapAction();
	protected abstract CallServiceTask getCallServiceTask();
	protected abstract boolean getDebugSetting();

	protected abstract class CallServiceTask extends AsyncTask<SoapSerializationEnvelope, Void, SoapSerializationEnvelope> {
		Throwable throwable;
		@Override
		protected SoapSerializationEnvelope doInBackground(SoapSerializationEnvelope... params) {
			HttpTransportSE httpTransport = new HttpTransportSE(AbstractCommunicationsProvider.URL);
			httpTransport.debug = getDebugSetting();
			SoapSerializationEnvelope soapEnvelope = params[0];
			try {
				httpTransport.call(getSoapAction(), soapEnvelope);
			} catch (Throwable t) {
				this.throwable = t;
			}
			if(getDebugSetting()){
				Log.d("CallServiceTask", "HTTP REQUEST:\n" + httpTransport.requestDump);
				Log.d("CallServiceTask", "HTTP RESPONSE:\n" + httpTransport.responseDump); 
			}
			return soapEnvelope;
		}

		@Override
		protected abstract void onPostExecute(SoapSerializationEnvelope envelope);
	}
}
